package com.tarena.lbs.business.servcie.Impl;

import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.base.enums.BusinessGroupResultEnum;
import com.tarena.lbs.business.constant.BusinessTypes;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.common.enums.PassportResultEnum;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tarena.lbs.business.servcie.BusinessService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessRepository businessRepository;
    @DubboReference
    private AttachApi attachApi;

    @Override
    public PageResult<BusinessVO> pageList(BusinessQuery query) {
        List<BusinessPO> pageResult = businessRepository.findPage(query);
        log.info("查询商家列表结果:{}",pageResult);
        List<BusinessVO> businessVOList;
        if(pageResult.isEmpty()){
            log.info("查询商家列表结果为空");
            PageResult<BusinessVO> pageResultVO = new PageResult<>(query);
            pageResultVO.setTotal((long) pageResult.size());
            return pageResultVO;
        }
        businessVOList = new ArrayList<>();
        for (BusinessPO businessPO : pageResult) {
            BusinessVO businessVO = new BusinessVO();
            BeanUtils.copyProperties(businessPO,businessVO);
            businessVOList.add(businessVO);
        }
        PageResult<BusinessVO> pageResultVO = new PageResult<>(query);
        pageResultVO.setTotal((long) pageResult.size());
        pageResultVO.setObjects(businessVOList);
        return pageResultVO;
    }

    @Override
    //事务回滚
    @Transactional(rollbackFor = Exception.class)
    public void saveBusiness(BusinessParam param) throws BusinessException {
        //检验用户是否登录
        //检验用户角色是否是商家
        checkLoginRoles(Roles.ADMIN);
        if(param.getId() != null){
            BusinessPO businessPO = new BusinessPO();
            BeanUtils.copyProperties(param,businessPO);
            if(param.getBusinessStatus() == 2){
                businessPO.setEntryTime(new Date());
                businessPO.setAuditRemarks(param.getAuditRemarks());
            }
            businessRepository.updateBusiness(businessPO);
            return;
        }

        // 检查商家名称是否已存在
        BusinessPO businessPOExist = businessRepository.selectByNickname(param.getBusinessName());
        if(businessPOExist != null){
            log.info("商家名称已存在:{}",param.getBusinessName());
            throw new BusinessException(BusinessGroupResultEnum.BUSINESS_NAME_EXIST);
        }
        Integer id = businessRepository.saveBusiness(param);
        //绑定图片
        if(param.getBusinessLicense() == null || param.getBusinessLogo() == null){
            log.info("商家营业执照或logo为空");
        }else {
            bindPictures(id, param);
        }
    }

    @Override
    public BusinessStoreVO busiStoreDetail(Integer businessId) throws BusinessException {
        BusinessPO businessPO = businessRepository.selectById(businessId);
        BusinessStoreVO businessStoreVO = new BusinessStoreVO();
        BeanUtils.copyProperties(businessPO,businessStoreVO);
        log.info("查询商家详情结果:{}",businessStoreVO);
        checkLoginRoles(Roles.ADMIN);
        return businessStoreVO;

    }

    private void bindPictures(Integer id, BusinessParam param) throws BusinessException {
        List<PicUpdateParam> picParams = new ArrayList<>();
        //准备插入营业执照
        PicUpdateParam picUpdateParam = new PicUpdateParam();
        picUpdateParam.setBusinessId(id);
        //获取营业执照url
        String businessLicense = param.getBusinessLicense();
        UUID uuidLicense = UUID.fromString(businessLicense);
        picUpdateParam.setFileUuid(uuidLicense.toString());
        //100 营业执照
        picUpdateParam.setBusinessType(BusinessTypes.BIZ_LICENSE);
        picParams.add(picUpdateParam);
        //准备绑定logo
        PicUpdateParam picUpdateParam1 = new PicUpdateParam();
        //插入与商家绑定的ID
        picUpdateParam.setBusinessId(id);
        //200 商家logo
        picUpdateParam1.setBusinessType(BusinessTypes.BIZ_LOGO);
        //获取logo图片地址
        String businessLogo = param.getBusinessLogo();
        UUID uuidLogo = UUID.fromString(businessLogo);
        picUpdateParam1.setFileUuid(uuidLogo.toString());
        //绑定图片,将营业执照与logo存储
        picParams.add(picUpdateParam1);
        boolean result = attachApi.batchUpdateBusiness(picParams);
        Asserts.isTrue(!result,new BusinessException("-2","业务绑定失败"));
    }

    private void checkLoginRoles(Roles roles) throws BusinessException {
        //检验用户是否登录
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null){
            throw new BusinessException(PassportResultEnum.USER_NOT_LOGIN);
        }
        //检验用户角色是否是商家
        if (userPrinciple.getRole() != Roles.ADMIN){
            throw new BusinessException(BusinessGroupResultEnum.USER_ROLE_ERROR);
        }
    }

}
